package com.huaweicloud.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.huaweicloud.persistent.entity.BsUserScheme;
import com.huaweicloud.persistent.entity.CoCompany;
import com.huaweicloud.persistent.entity.CoCompanyUser;
import com.huaweicloud.persistent.mapper.CoCompanyUserMapper;
import com.huaweicloud.persistent.repository.BsUserSchmeRepository;
import com.huaweicloud.persistent.repository.CompanyRepository;
import com.huaweicloud.service.ICompanyService;
import com.huaweicloud.vo.CompanyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

@Service
public class CompanyServiceImpl implements ICompanyService {

    @Autowired
    CompanyRepository companyRepository;
    @Autowired
    BsUserSchmeRepository bsUserSchmeRepository;
    @Autowired
    CoCompanyUserMapper coCompanyUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addCompanyInfo(CompanyVo companyVo) {
        // 创建企业信息
        CoCompany coCompany = new CoCompany();
        coCompany.setId(UUID.randomUUID().toString().replace("-", ""));
        coCompany.setName(companyVo.getName());
        coCompany.setCreateTime(new Date());
        companyRepository.save(coCompany);
        // 获取scheme名称
        String dataBaseSchemeName = companyVo.getNameEn() + "_company";
        // 创建用户跟scheme的关系
        BsUserScheme bsUserScheme = new BsUserScheme();
        bsUserScheme.setSchemeName(dataBaseSchemeName);
        bsUserScheme.setUserName(companyVo.getManagerId());
        BsUserScheme schemeByUserId = bsUserSchmeRepository.findSchemeByUserId(companyVo.getManagerId(), dataBaseSchemeName);
        if (schemeByUserId == null) {
            bsUserSchmeRepository.getBaseMapper().insert(bsUserScheme);
        }
        // 创建公司scheme
        companyRepository.getBaseMapper().createCompanyDataBase(dataBaseSchemeName);
        // 查询表是否存在
        String coCompanyUser = companyRepository.getBaseMapper().findTableName("co_company_user", dataBaseSchemeName);
        // 创建公司相关表
        if (StringUtils.isBlank(coCompanyUser)) {
            companyRepository.getBaseMapper().createCompanyTable(dataBaseSchemeName, "co_company_user");
        }
        // 创建公司用户
        CoCompanyUser companyUser = new CoCompanyUser();
        companyUser.setUserId(companyVo.getManagerId());
        companyUser.setPassword("123456");
        companyUser.setCompanyId(coCompany.getId());
        companyUser.setSchemeName(dataBaseSchemeName);
        coCompanyUserMapper.createCompanyUser(companyUser);
        return coCompany.getId();
    }
}
